//
//  DiscoverFeedsViewController.m
//  rss_reader
//
//  Created by Oleg Soldatoff on 4/12/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DiscoverFeedsViewController.h"

@implementation DiscoverFeedsViewController
@synthesize tableView=_tableView;
@synthesize urlToDiscoverFeeds = _urlToDiscoverFeeds;
@synthesize arrayWithFeeds = _arrayWithFeeds;
@synthesize arrayWithSelectedFeeds = _arrayWithSelectedFeeds;
@synthesize base = _base;
@synthesize siteID = _siteID;

- (id)init
{
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
      self.title = NSLocalizedString(@"Discover RSS", @"Discover RSS");

      [[NSNotificationCenter defaultCenter] addObserver:self 
                                               selector:@selector(pocessNotification:)  
                                                   name:@"xmlRecieved" 
                                                 object:nil]; 
      
      [[NSNotificationCenter defaultCenter] addObserver:self 
                                               selector:@selector(pocessNotification:)  
                                                   name:@"ErrorInNetwork" 
                                                 object:nil]; 
      self.base = [[[DataBase alloc]init]autorelease];
      
    }
    return self;
}

- (void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self]; 
  [_base release];
  _base = nil;
  [_arrayWithFeeds release]; 
  _arrayWithFeeds = nil;
  [_arrayWithSelectedFeeds release];
    _arrayWithSelectedFeeds = nil;
  [super dealloc];
}


- (void)viewDidUnload
{
  [super viewDidUnload];
  // Release any retained subviews of the main view.
  // e.g. self.myOutlet = nil;
  self.base = nil;
}


- (void)viewDidLoad
{
  [super viewDidLoad];
  
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
  self.view.backgroundColor = [UIColor lightGrayColor];
  self.tableView = [[[UITableView alloc] initWithFrame:CGRectMake(0,  50, 320, 366)] autorelease]; 
  self.tableView.delegate = self;
  self.tableView.dataSource = self;
  [self.view addSubview: self.tableView];
  
  
  self.urlToDiscoverFeeds = [[[UITextField alloc] initWithFrame:CGRectMake(10, 10, 300, 27)]autorelease];
  self.urlToDiscoverFeeds.borderStyle = UITextBorderStyleRoundedRect;
  //self.urlToDiscoverFeeds.textColor = [UIColor blackColor]; //text color
  //self.urlToDiscoverFeeds.font = [UIFont systemFontOfSize:9.0];  //font size
  self.urlToDiscoverFeeds.placeholder = @"Your favourite site";  //place holder
  self.urlToDiscoverFeeds.backgroundColor = [UIColor whiteColor]; //background color
  self.urlToDiscoverFeeds.autocorrectionType = UITextAutocorrectionTypeNo;	// no auto correction support
  self.urlToDiscoverFeeds.keyboardType = UIKeyboardTypeURL;  // type of the keyboard
  self.urlToDiscoverFeeds.returnKeyType = UIReturnKeyGo;  // type of the return key
  self.urlToDiscoverFeeds.clearButtonMode = UITextFieldViewModeWhileEditing;	// has a clear 'x' button to the right
  self.urlToDiscoverFeeds.delegate = self;	
  [self.view addSubview:  self.urlToDiscoverFeeds];
  
  UIToolbar *actionToolbar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0, 416, 320, 44)]autorelease];
  //actionToolbar.barStyle = UIBarStyleBlackTranslucent;
  
  UIBarButtonItem *saveButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave 
                                                          target:self 
                                                          action:@selector(savePressed:)]autorelease];
  
  
  
  
  UIBarButtonItem *cancelButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel 
                                                            target:self 
                                                            action:@selector(cancelPressed:)]autorelease];
  
  UIBarButtonItem *flexibleSpaceButtonItem = [[[UIBarButtonItem alloc]
                                               initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                               target:nil action:nil] autorelease];
  
  [actionToolbar setItems:[NSArray arrayWithObjects:
                           saveButton,
                           flexibleSpaceButtonItem,
                           cancelButton, nil]];
  
  [self.view addSubview:actionToolbar];
  
}

- (NSMutableArray *) arrayWithSelectedFeeds  {
  
  if ( nil == _arrayWithSelectedFeeds ) {
    
    NSNumber *siteID = [NSNumber numberWithInt:0];
    _arrayWithSelectedFeeds = [[[NSMutableArray alloc]init]autorelease];
    
    if (siteID == [self.base siteIDForSite: self.urlToDiscoverFeeds.text] ) {
      NSLog(@"WE are in new arr");
    } else {
      self.siteID =  [self.base siteIDForSite: self.urlToDiscoverFeeds.text];
      NSLog(@"WE found siteID - %@", [self.base siteIDForSite: self.urlToDiscoverFeeds.text]);
      
      for (NSDictionary *dic in [self.base baseFeedsForSiteID: [self.siteID intValue]]) {
        [_arrayWithSelectedFeeds addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                                          [dic valueForKey: @"URL"], @"href",
                                                          [dic valueForKey: @"NAME"], @"title", nil ]];
      }
      NSLog(@"WE found array of feeds %@",  _arrayWithSelectedFeeds);
 
    }
    [_arrayWithSelectedFeeds retain];
  }
  return _arrayWithSelectedFeeds;
  
}

- (void) savePressed: (id) sender {
  
  [self.base addFeeds:self.arrayWithSelectedFeeds forSite:self.urlToDiscoverFeeds.text];
  [self dismissModalViewControllerAnimated:YES];
  
}

- (void) cancelPressed: (id) sender {
  
  [self dismissModalViewControllerAnimated:YES];
  
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
  
     return [self.arrayWithFeeds count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"Cell";
  
  UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                   reuseIdentifier:CellIdentifier] autorelease];
    cell.accessoryType = UITableViewCellAccessoryNone;
  }
    
/*  {
    href = "http://news.tut.by/rss/companynews.rss";
    rel = alternate;
    title = "TUT.BY - \U041d\U043e\U0432\U043e\U0441\U0442\U0438 \U043a\U043e\U043c\U043f\U0430\U043d\U0438\U0439";
    type = "application/rss+xml";
  }
*/
   cell.accessoryType = UITableViewCellAccessoryNone;
  
  for (NSDictionary *dicFeedsOfSite in self.arrayWithSelectedFeeds) {
      
    if ( [[dicFeedsOfSite valueForKey: @"href"] 
                  isEqual:
         [[self.arrayWithFeeds objectAtIndex:indexPath.row] valueForKey:@"href"] ] ) 
    {
         cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
  
  }
  
  
  
    cell.textLabel.text =[[self.arrayWithFeeds objectAtIndex:indexPath.row] valueForKey:@"title"];
    return cell;    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
  UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

  if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
      
    cell.accessoryType = UITableViewCellAccessoryNone;
    for (NSDictionary *dicSelectedFeedsOfSite in self.arrayWithSelectedFeeds) 
    {
      
      if ( [[dicSelectedFeedsOfSite valueForKey: @"href"] 
            isEqual:
            [[self.arrayWithFeeds objectAtIndex:indexPath.row] valueForKey:@"href"] ] ) 
     {
        [self.arrayWithSelectedFeeds removeObject:dicSelectedFeedsOfSite];
        break;
      }
    }

  } else {
  
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    [self.arrayWithSelectedFeeds addObject:[self.arrayWithFeeds objectAtIndex:indexPath.row]];
    
  }
  
}





- (BOOL)textFieldShouldReturn:(UITextField *)textField {

  
   self.arrayWithSelectedFeeds = nil;
  
  if ( [self.urlToDiscoverFeeds.text hasPrefix:@"http://"] == NO ) {
    self.urlToDiscoverFeeds.text = [NSString stringWithFormat:@"http://%@", self.urlToDiscoverFeeds.text]; 
  }
  [NSThread detachNewThreadSelector:@selector(startTheBackgroundJob) toTarget:self withObject:nil];  
  [textField resignFirstResponder];
  return NO;

}

- (void)startTheBackgroundJob {  
  UIApplication* app = [UIApplication sharedApplication];
  app.networkActivityIndicatorVisible = YES;
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
 
  [[Network sharedNetwork] giveXML: [NSDictionary dictionaryWithObject:self.urlToDiscoverFeeds.text forKey:@"URL"]];
  
  //[[[[Network alloc]init]autorelease] giveXML:self.urlToDiscoverFeeds.text];

  NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
  //[runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
  while ([runLoop runMode:NSDefaultRunLoopMode
               beforeDate:[NSDate distantFuture]]);
  
  
  [pool release];  
  //UIApplication* app = [UIApplication sharedApplication];
  app.networkActivityIndicatorVisible = NO; 
}  


- (void) pocessNotification:(NSNotification *) notification { 
  
  if ([[notification name] isEqualToString:@"xmlRecieved"]) { 
    
    self.arrayWithFeeds = [XMLParser arrayWithFeeds: [[Network sharedNetwork] receivedData]];
    [self.tableView reloadData];
    
    NSLog (@"%d", [self.arrayWithFeeds count]); 
     
    
  } else if (  [[notification name] isEqualToString:@"ErrorInNetwork"] ) {
    
   
    [[[[UIAlertView alloc]initWithTitle:@"Network error" message:@"Problems in network" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil]autorelease]show];
     
    
  }
  
} 




@end
